package com.ncu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.ncu.gulimall.cart.feign.ProductFeignService;
import com.ncu.gulimall.cart.interceptor.CartInterceptor;
import com.ncu.gulimall.cart.service.CartService;
import com.ncu.gulimall.cart.to.UserInfoTo;
import com.ncu.gulimall.cart.vo.Cart;
import com.ncu.gulimall.cart.vo.CartItem;
import com.ncu.gulimall.cart.vo.SkuInfoVo;
import com.ncu.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CartServiceImpl implements CartService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ProductFeignService productFeignService;

    @Autowired
    private ThreadPoolExecutor executor;

    private static final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) throws ExecutionException, InterruptedException {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();

        String res = (String) cartOps.get(skuId.toString());

        if (StringUtils.isEmpty(res)) {
            CartItem cartItem = new CartItem();
            //购物车中没有这个商品，将商品信息添加到购物车
            cartItem.setCheck(true);
            cartItem.setCount(num);
            cartItem.setSkuId(skuId);

            CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
                //1.远程查询当前添加的商品的信息
                R r = productFeignService.getSkuInfo(skuId);
                SkuInfoVo skuInfo = r.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                });
                cartItem.setImage(skuInfo.getSkuDefaultImg());
                cartItem.setTitle(skuInfo.getSkuTitle());
                cartItem.setPrice(skuInfo.getPrice());
            }, executor);

            CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
                //3.远程查询销售属性组合
                List<String> values = productFeignService.getSkuSaleAttrValues(skuId);
                cartItem.setSkuAttr(values);
            }, executor);

            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();

            String s = JSON.toJSONString(cartItem);
            cartOps.put(skuId.toString(), s);

            return cartItem;
        } else {
            //购物车中有这个商品，修改数量即可
            CartItem cartItem = JSON.parseObject(res, CartItem.class);
            cartItem.setCount(cartItem.getCount() + num);

            cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));

            return cartItem;
        }


    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        String res = (String) cartOps.get(skuId.toString());
        return JSON.parseObject(res, CartItem.class);
    }

    @Override
    public Cart getCart() throws ExecutionException, InterruptedException {
        //1.从拦截器中获取用户信息，由于是统一线程，所以可以localThread
        UserInfoTo userInfo = CartInterceptor.threadLocal.get();

        Cart cart = new Cart();
        if (userInfo.getUserId() != null) {
            //登陆状态
            String cartKey = CART_PREFIX + userInfo.getUserId();
            //判断当前是否合并了临时购物车的数据
            //1.获取临时购物车中的数据
            String tempCartKey = CART_PREFIX + userInfo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKey);
            if (tempCartItems != null) {
                //需要合并购物车
                for (CartItem tempCartItem : tempCartItems) {
                    addToCart(tempCartItem.getSkuId(), tempCartItem.getCount());
                }
                //合并之后清除临时购物车的数据

                clearCart(tempCartKey);
            }
            //2.获取登录后的购物车(包含合并的临时购物车)
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        } else {
            //未登录状态
            String cartKey = CART_PREFIX + userInfo.getUserKey();
            List<CartItem> cartItems = getCartItems(cartKey);
            cart.setItems(cartItems);
        }
        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCheck(check == 1);
        String jsonString = JSON.toJSONString(cartItem);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), jsonString);
    }

    @Override
    public void changeItemCount(Long skuId, Integer num) {
        CartItem cartItem = getCartItem(skuId);
        cartItem.setCount(num);
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations<String, Object, Object> cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        if (userInfoTo.getUserId() == null) {
            return null;
        } else {
            String cartKey = CART_PREFIX + userInfoTo.getUserId();
            List<CartItem> cartItems = this.getCartItems(cartKey);
            //获取所有选中的购物项
            List<CartItem> collect = null;
            if (cartItems != null) {
                collect = cartItems.stream()
                        .filter(CartItem::getCheck)
                        .peek(item -> {
                            // 更新为最新价格
                            R price = productFeignService.getPrice(item.getSkuId());
                            String data = (String) price.get("data");
                            item.setPrice(new BigDecimal(data));
                        })
                        .collect(Collectors.toList());
            }
            return collect;
        }
    }

    /**
     * 绑定一个操作哈希结构购物车的操作类型
     *
     * @return
     */
    private BoundHashOperations<String, Object, Object> getCartOps() {
        //1.从拦截器中获取用户信息，由于是统一线程，所以可以localThread
        UserInfoTo userInfo = CartInterceptor.threadLocal.get();

        String cartKey = "";
        //2.判断用户是否是登陆的，由此决定用临时购物车还是用户购物车
        if (userInfo.getUserId() != null) {
            //登陆的
            cartKey = CART_PREFIX + userInfo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfo.getUserKey();
        }

        return redisTemplate.boundHashOps(cartKey);
    }

    /**
     * 获取指定购物车中的购物项
     *
     * @param cartKey
     * @return
     */
    private List<CartItem> getCartItems(String cartKey) {
        BoundHashOperations<String, Object, Object> hashOps = redisTemplate.boundHashOps(cartKey);
        List<Object> values = hashOps.values();
        if (values != null && values.size() > 0) {
            List<CartItem> collect = values.stream().map(o -> {
                String str = (String) o;
                return JSON.parseObject(str, CartItem.class);
            }).collect(Collectors.toList());
            return collect;
        }
        return null;
    }
}
